package com.jkhan.demo.threads;

import java.util.concurrent.Semaphore;

public class Demo01 {
    public static void main(String[] args) {

        Semaphore semaphore = new Semaphore(2);

        com.jkhan.demo.threads.Person p1 = new com.jkhan.demo.threads.Person(semaphore, "A");
        p1.start();
        com.jkhan.demo.threads.Person p2 = new com.jkhan.demo.threads.Person(semaphore, "B");
        p2.start();
        com.jkhan.demo.threads.Person p3 = new com.jkhan.demo.threads.Person(semaphore, "C");
        p3.start();
    }
}

class Person extends Thread {

    private Semaphore semaphore;

    public Person(Semaphore semaphore, String name) {
        setName(name);
        this.semaphore = semaphore;
    }

    @Override
    public void run() {
        System.out.println(getName() + " is waiting...");
        try {
            semaphore.acquire();
            System.out.println(getName() + " is servicing...");
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(getName() + " is done!");
        semaphore.release();
    }
}
